import React from 'react'
import { connect } from 'dva'
import { Page } from 'components'
import OrderFilterUnExpand from './OrderFilterUnExpand'
import { Button, Divider, Badge, Tag, Card, Table, Alert, Input } from 'antd'
import { LwjDialog } from 'components'
import PageHeaderLayout from 'components/Layout/PageHeaderLayout'
import moment from 'moment'
import {
  orderStatus,
  orderStatusColor,
  contractStatusArr,
  productType,
  contractOrderStatus,
  contractCancelStatus,
  checkIsStoreRoles,
  checkCurrentRole,
  storeAdminArr,
  storeEmployeeArr,
  designerArr,
  sourceSystem
} from 'utils/enumConfig'
import LwjTable from './LwjTable'
import styles from './index.less'
import ContractDetailModal from './ContractDetailModal'
import { showButton } from 'utils/promissionFilter'
import { debug } from 'util';

const CheckableTag = Tag.CheckableTag

const orderLists = ({ location, dispatch, orderList, app, loading }) => {
  const {
    items,
    isExpand,
    pagination,
    queryParam,
    listState,
    selectedTags,
    isShowContractDetailModal,
    currentContractDetail,
    currentListType,
    countContracts,
    tagQueryParam,
  } = orderList

  const { user, resources } = app

  const breadcrumbList = [
    {
      title: '订单管理'
    },
    {
      title: listState === 'ALL' ? '全部订单' : '待办订单'
    }
  ]

  const filterContractOrderType = {
    type: 'select',
    id: 'contractOrderType',
    title: '合同类型',
    options: [
      {
        value: '',
        name: '全部'
      },
      {
        value: 'CUSTOMIZE',
        name: '定制'
      }, {
        value: 'END',
        name: '成品'
      }
    ]
  }

  const filterNum = {
    type: 'input',
    id: 'customerName',
    title: '客户姓名'
  }

  // 定义筛选属性 表单相关
  const filterProps = {
    filterItems: [
      currentListType === "salesOrder" ? filterNum : filterContractOrderType,
      {
        type: 'input',
        id: 'contractNum',
        title: '合同号'
      }, {
        type: 'select',
        id: 'salesOrderStatus',
        title: '订单状态',
        options: [
          {
            value: '',
            name: '全部'
          },
          {
            value: 'DRAFT',
            name: '待下单'
          }, {
            value: 'IN_SALES_PROGRESS',
            name: '已下单'
          }
        ]
      }, {
        type: 'input',
        id: 'num',
        title: '订单编号'
      },
      currentListType === "salesOrder" ? filterContractOrderType : filterNum,
      , {
        type: 'input',
        id: 'customerPhoneNum',
        title: '客户手机号'
      }, {
        type: 'input',
        id: 'salesmanName',
        title: '销售员'
      }, {
        type: 'input',
        id: currentListType === "salesOrder" ? 'salesDistributorName' : "distributorName",
        title: '所属门店'
      }, {
        type: 'dateRule',
        id: 'createTime',
        dateFormat: 'YYYY/MM/DD HH:mm:ss',
        title: '创建时间'
      }, {
        type: 'select',
        id: 'sourceSystem',
        title: '订单来源',
        options: [
          {
            value: '',
            name: '全部'
          },
          {
            value: 'NULL',
            name: '分销'
          }, {
            value: 'LWJ_SHOP',
            name: '丽维家商城'
          }, {
            value: 'YOUZAN_SHOP',
            name: '有赞商城'
          }, {
            value: 'WX_LITE',
            name: '小程序'
          }
        ]
      }, currentListType === "contract" && {
        type: 'input',
        id: 'consigneeName',
        title: '收货人姓名'
      }, currentListType === "contract" && {
        type: 'input',
        id: 'consigneePhoneNum',
        title: '收货人手机号'
      }
    ],
    onFilterChange(value) {
      dispatch({
        type: 'orderList/query',
        payload: {
          ...value
        }
      })
    },
    isExpand,
    noExpand() {
      dispatch({ type: 'orderList/unExpandFilter', payload: {} })
    },
    expand() {
      dispatch({ type: 'orderList/expandFilter', payload: {} })
    }
  }

  // 列表相关
  const listProps = {
    dataSource: items,
    loading: loading.effects['orderList/query'],
    pagination,
    pageChangeAction: 'orderList/query',
    dispatch,
    location,
  }


  const salesOrderColumns = [
    {
      title: '订单编号',
      dataIndex: 'num',
      key: 'num',
      align: 'left',
      width: 200,
      render: (text, record) => (
        <span>
          <a className={styles.a} onClick={() => onShowDetail(record)}>{record.num}</a>
          <Button
            onClick={() => onShowDetail(record)}
            size="small"
            shape="circle"
            icon="search"
            style={{ marginLeft: 5 }} />
        </span>
      )
    }, {
      title: '客户姓名',
      dataIndex: 'customerName',
      key: 'customerName'
    }, {
      title: '客户手机号',
      dataIndex: 'customerPhoneNum',
      key: 'customerPhoneNum'
    }, {
      title: '销售员',
      dataIndex: 'salesmanName',
      key: 'salesmanName'
    }, {
      title: '所属门店',
      dataIndex: 'salesDistributorName',
      key: 'salesDistributorName'
    }, {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: true,
      render: (text, record, index) => (moment(record.createTime).format('YYYY-MM-DD HH:mm:ss'))
    }, {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'left',
      render: (text, record) => (
        <span>
          <a onClick={() => updateOrder(record)}>编辑</a>
          {record.status === 'DRAFT' && <Divider type="vertical" />}
          {record.status === 'DRAFT' && <a onClick={() => deleteOrder(record)}>删除</a>}
        </span>
      )
    }
  ]


  // 合同展开嵌套表单
  const expandColumns = [
    {
      title: '合同号',
      dataIndex: 'contractNum',
      key: 'contractNum',
      align: 'left',
      width: 100,
      render: (text, record) => (
        <span>
          <a className={styles.a} onClick={() => onShowContractDetail(record)}>{record.contractNum}</a>
        </span>
      )
    }, {
      title: '合同类型',
      dataIndex: 'contractOrderType',
      key: 'contractOrderType',
      width: 50,
      render: (text, record, index) => (record.contractOrderType === 'END' ? <Tag color="#2db7f5">成品</Tag> : < Tag
        color="#87d068"> 定制</Tag>)
    }, {
      title: '产品类型',
      dataIndex: 'productType',
      key: 'productType',
      width: 50,
      render: (text, record, index) => (productType[record.productType])
    }, {
      title: '是否需要设计',
      dataIndex: 'designNeeded',
      key: 'designNeeded',
      width: 100,
      render: (text, record, index) => (record.designNeeded ? '是' : '否')
    }, {
      title: '是否推送到丽维家',
      dataIndex: 'pushToOMSNeeded',
      key: 'pushToOMSNeeded',
      width: 100,
      render: (text, record, index) => (record.pushToOMSNeeded === null ? '' : record.pushToOMSNeeded ? '是' : '否')
    }, {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (text, record, index) => (
        record.contractCancelStatus === 'NULL' ? contractOrderStatus[record.status] : contractOrderStatus[record.status] + '(' + contractCancelStatus[record.contractCancelStatus] + ')'
      )
    }, {
      title: '订单来源',
      dataIndex: 'sourceSystem',
      key: 'sourceSystem',
      width: 100,
      render: (text, record, index) => (
        <div>
          {_.isEmpty(sourceSystem[record.sourceSystem]) ? "分销系统" : sourceSystem[record.sourceSystem]}
          <Tag color={_.isEmpty(sourceSystem[record.sourceSystem]) ? "green" : record.sourceSystem === "NULL" ? "green" : "red"} style={{ marginLeft: 10 }}>{_.isEmpty(sourceSystem[record.sourceSystem]) ? "分" : record.sourceSystem === "NULL" ? "分" : "三"}</Tag>
        </div>
      )
    }, {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 100,
      render: (text, record, index) => (moment(record.updateTime).format('YYYY-MM-DD HH:mm:ss'))
    }, {
      title: '操作',
      dataIndex: 'contractHandle',
      key: 'contractHandle',
      width: 100,
      render: (text, record) => (
        <span>
          <a onClick={() => onShowContractDetail(record)}>查看</a>
        </span>
      )
    }
  ]

  const contractColumns = [
    {
      title: '合同号',
      dataIndex: 'contractNum',
      key: 'contractNum',
      align: 'left',
      render: (text, record) => (
        <span>
          <a className={styles.a} onClick={() => onShowContractDetail(record)}>{record.contractNum}</a>
          <Button
            onClick={() => onShowContractDetail(record)}
            size="small"
            shape="circle"
            icon="search"
            style={{ marginLeft: 5 }} />
        </span>
      )
    }, {
      title: '订单号',
      dataIndex: 'salesOrderNum',
      key: 'salesOrderNum',
      align: 'left',
    }, {
      title: '合同类型',
      dataIndex: 'contractOrderType',
      key: 'contractOrderType',
      render: (text, record, index) => (record.contractOrderType === 'END' ? <Tag color="#2db7f5">成品</Tag> : < Tag
        color="#87d068"> 定制</Tag>)
    }, {
      title: '产品类型',
      dataIndex: 'productType',
      key: 'productType',
      render: (text, record, index) => (productType[record.productType])
    }, {
      title: '客户姓名',
      dataIndex: 'customerName',
      key: 'customerName',
      align: 'left',
    }, {
      title: '客户手机号',
      dataIndex: 'customerPhoneNum',
      key: 'customerPhoneNum',
      align: 'left',
    }, {
      title: '所属门店',
      dataIndex: 'salesDistributorName',
      key: 'salesDistributorName',
      align: 'left',
    }, {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text, record, index) => (
        record.contractCancelStatus === 'NULL' ? contractOrderStatus[record.status] : contractOrderStatus[record.status] + '(' + contractCancelStatus[record.contractCancelStatus] + ')'
      )
    }, {
      title: '订单来源',
      dataIndex: 'sourceSystem',
      key: 'sourceSystem',
      render: (text, record, index) => (
        <div>
          {_.isEmpty(sourceSystem[record.sourceSystem]) ? "分销系统" : sourceSystem[record.sourceSystem]}
          <Tag color={_.isEmpty(sourceSystem[record.sourceSystem]) ? "green" : record.sourceSystem === "NULL" ? "green" : "red"} style={{ marginLeft: 10 }}>{_.isEmpty(sourceSystem[record.sourceSystem]) ? "分" : record.sourceSystem === "NULL" ? "分" : "三"}</Tag>
        </div>
      )
    }, {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      sorter: true,
      render: (text, record, index) => (moment(record.updateTime).format('YYYY-MM-DD HH:mm:ss'))
    }, {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: true,
      render: (text, record, index) => (moment(record.createTime).format('YYYY-MM-DD HH:mm:ss'))
    }, {
      title: '操作',
      dataIndex: 'contractHandle',
      key: 'contractHandle',
      render: (text, record) => (
        <span>
          <a onClick={() => updateOrder(record)}>编辑</a>
        </span>
      )
    }
  ]
  // 合同详情 props
  const contractDetailModalProps = {
    title: '合同详情',
    visible: isShowContractDetailModal,
    destroyOnClose: true,
    width: 1000,
    currentContractDetail,
    footer: null,
    onCancel(record) {
      dispatch({
        type: 'orderList/hideContractDetailModal',
        payload: {}
      })
    },
    showOrderQuote: showButton('contractDetail.orderQuoteSummary', resources, user),
  }

  const getExpandData = (record) => {
    if (record.contractOrderSummaries.length > 0) {
      return (
        <Table
          rowKey={record => record.id}
          className={styles.expandTable}
          pagination={false}
          bordered={false}
          dataSource={record.contractOrderSummaries}
          columns={expandColumns} />)
    } else {
      return (<span>暂无数据</span>)
    }
  }

  /**
   * 添加意向单
   */
  const toCreateSalesOrder = () => {
    dispatch({ type: 'orderList/toCreateSalesOrder', payload: {} })
  }

  /**
   * 查看详情
   * @param {*} record
   */
  const onShowDetail = (record) => {
    dispatch({
      type: 'orderList/onShowDetail',
      payload: {
        record: record
      }
    })
  }
  /**
   * 刷新订单状态
   */
  const freshData = () => {
    dispatch({
      type: 'orderList/query',
      payload: {
        ...queryParam
      }
    })
  }

  /**
   * 删除意向订单
   */
  const deleteOrder = (record) => {
    LwjDialog.confirm({
      title: '您确认要删除该意向单？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'orderList/deleteOrder',
          payload: {
            salesOrderId: record.id
          }
        })
      },
      onCancel() { }
    })
  }

  /**
   * 编辑订单
   * @param {*} record
   */
  const updateOrder = (record) => {
    if (currentListType === "salesOrder") {
      if (record.status === 'DRAFT') {
        dispatch({
          type: 'orderList/toUpdateSalesOrder',
          payload: {
            salesOrderId: record.id
          }
        })
      }
      if (record.status === 'IN_SALES_PROGRESS') {
        dispatch({
          type: 'orderList/toUpdateContractOrder',
          payload: {
            salesOrderId: record.id
          }
        })
      }
    } else {
      dispatch({
        type: 'orderList/toUpdateContractOrder',
        payload: {
          salesOrderId: record.salesOrderId
        }
      })
    }

  }

  /**
   * 选中标签方法
   * @param {*} tag
   * @param {*} checked
   */
  const handleChange = (tag, checked) => {
    const nextSelectedTags = checked ? tag === "STORE_OMS" ?
      ["PUBLISHED", "PENDING_CONFIRM_OMS_QUOTED"] : [tag] :
      // selectedTags.filter(t => t !== tag)
      []
    dispatch({
      type: 'orderList/queryBySelectedTags',
      payload: {
        selectedTags: nextSelectedTags
      }
    })
  }

  /**
   * 重置标签方法
   */
  const resetSelectTags = () => {
    dispatch({
      type: 'orderList/queryBySelectedTags',
      payload: {
        selectedTags: []
      }
    })
  }

  /**
   * 合同订单详情
   * @param {*} record
   */
  const onShowContractDetail = (record) => {
    dispatch({
      type: 'orderList/onShowContractDetail',
      payload: {
        contractOrderId: record.id,
        salesOrderId: record.salesOrderId
      }
    })
  }

  const buildTabSearch = (tag) => {
    if (checkIsStoreRoles(app.user) && tag.status === "PUBLISHED") {
      return (
        <CheckableTag
          color="#2db7f5"
          key="STORE_OMS"
          checked={selectedTags.indexOf(tag.status) > -1}
          style={{ marginLeft: 10 }}
          onChange={checked => handleChange("STORE_OMS", checked)}
        >
          待生产
          </CheckableTag>
      )
    } else if (checkIsStoreRoles(app.user) && tag.status === "PENDING_CONFIRM_OMS_QUOTED") {
      return
    }
    //selectedTags.indexOf(tag.status) > -1
    else if (!_.isEmpty(tag.status)) {
      const isChecked = () => {
        if (tagQueryParam.designNeeded) {
          return (selectedTags[0] + "_NEED").indexOf(tag.status) > -1
        } else if (tagQueryParam.designNeeded != null && !tagQueryParam.designNeeded) {
          return (selectedTags[0] + "_NO_NEED").indexOf(tag.status) > -1
        }
        return selectedTags.indexOf(tag.status) > -1
      }
      return (
        <Badge key={tag.status} style={{ backgroundColor: '#57c9c2', color: 'white', boxShadow: '0 0 0 1px #d9d9d9 inset' }} count={listState === "ALL" ? null : countContracts[tag.status.toLowerCase()]}>
          <CheckableTag
            color="#2db7f5"
            key={tag.status}
            checked={isChecked()}
            style={{ marginLeft: 10 }}
            onChange={checked => handleChange(tag.status, checked)}
          >
            {tag.display}
          </CheckableTag>
        </Badge>
      )
    }
  }

  const checkCurrentType = (type) => {
    delete queryParam.distributorName
    dispatch({
      type: 'orderList/setCurrentShowList',
      payload: type
    })
    resetSelectTags();
    dispatch({
      type: 'orderList/query',
      payload: {
        ...queryParam
      }
    })
  }

  return (
    <PageHeaderLayout title={listState === 'ALL' ? '全部订单' : '待办订单'} breadcrumbList={breadcrumbList}>
      <Page inner>
        <ContractDetailModal {...contractDetailModalProps} />
        <OrderFilterUnExpand {...filterProps} />
        <div
          style={{
            textAlign: 'left',
            marginBottom: 20
          }}>
          <Button
            onClick={() => checkCurrentType(currentListType === "salesOrder" ? "contract" : "salesOrder")}
            type="block"
            icon="swap"
            style={{
              marginRight: 10
            }}>切换{currentListType === "salesOrder" ? "合同" : "意向单"}列表</Button>
          <Button
            onClick={freshData}
            type="primary"
            icon="sync"
            style={{
              marginRight: 10
            }}>刷新{currentListType === "salesOrder" ? "订单" : "合同"}状态</Button>
          {showButton('orderList.salesOrder.create', resources, user) && currentListType === "salesOrder" && listState === "myOrder" && <Button
            onClick={toCreateSalesOrder}
            icon="plus"
            type="primary"
            style={{
              marginRight: 10
            }}>添加意向单</Button>}
        </div>
        <div style={{ marginBottom: 10 }}>
          <Card type="inner">
            <h6 style={{ marginRight: 8, display: 'inline' }}>合同状态:</h6>
            {
              listState === "ALL" ? contractStatusArr.map(tag => (
                buildTabSearch(tag.deal ? tag : {})
              )) :
                checkCurrentRole(app.user) === "storeAdmin" ?
                  storeAdminArr.map(tag => (
                    buildTabSearch(tag.deal ? tag : {})
                  )) : checkCurrentRole(app.user) === "storeEmployee" ?
                    storeEmployeeArr.map(tag => (
                      buildTabSearch(tag.deal ? tag : {})
                    )) : checkCurrentRole(app.user) === "designer" ?
                      designerArr.map(tag => (
                        buildTabSearch(tag.deal ? tag : {})
                      )) :
                      contractStatusArr.map(tag => (
                        buildTabSearch(tag.deal ? tag : {})
                      ))
            }
            <Button type="primary" style={{ marginLeft: 9 }} size="small" onClick={() => resetSelectTags()}>重置</Button>
          </Card>
        </div>
        {currentListType === "salesOrder" ?
          <LwjTable {...listProps} columns={listState === "ALL" ? salesOrderColumns.filter((item) => item.key !== "handle") : salesOrderColumns}
            expandedRowRender={record => <div style={{ margin: 0 }}>{getExpandData(record)}</div>} />
          :
          <LwjTable {...listProps} columns={listState === "ALL" ? contractColumns.filter((item) => item.key !== "contractHandle") : contractColumns} />
        }

      </Page>
    </PageHeaderLayout>
  )
}

export default connect(({ orderList, app, loading }) => ({ orderList, app, loading }))(orderLists)
